import { createApp, nextTick } from 'vue'
import { Vue } from 'vue-demi'
import Message from './index.vue'

// type Fn = (e: { text: string; type: 'success' | 'error' | 'warn' }) => void
type Fn = {
  (e: { text: string; type: 'success' | 'error' | 'warn' }): void
  success?: (e: string) => void
  error?: (e: string) => void
  warn?(e: string): void
}

export const HmMessage: Fn = ({ text, type }) => {
  // 将Message组件的html渲染到body内
  //    1：通过createApp(组件)   2：通过mount渲染  mount(dom)
  const app = createApp(Message, {
    text: text,
    type: type,
    remove: remove
  })
  //   createApp(组件,用于传递给组件的props参数，它是一个对象)
  //   创建一个标签用于承载Message组件内容
  const div = document.createElement('div')
  //   给div加入一个class
  div.setAttribute('class', 'hmMessage')
  document.body.append(div)
  app.mount(div)

  // 排序
  //   div 下的.xtx-message的dom,依次递增的控制比如marginTop属性
  // 1：先取所有的dom  2:再处理div下的.xtx-message的dom的css
  function sortDiv () {
    nextTick(() => {
      const divDomArr = document.querySelectorAll('.hmMessage')
      for (let i = 0; i < divDomArr.length; i++) {
        ;(divDomArr[i].querySelector(
          '.xtx-message'
        ) as HTMLElement).style.marginTop = i * 80 + 'px'
      }
    })
  }
  sortDiv()
  // 销毁  app.unmount()
  function remove () {
    app.unmount()
    document.body.removeChild(div)
    sortDiv()
  }
}

const arr: ('success' | 'error' | 'warn')[] = ['success', 'error', 'warn']
arr.forEach(item => {
  HmMessage[item] = text => {
    HmMessage({ text, type: item })
  }
})

// HmMessage.success = text => {
//   HmMessage({ text, type: 'success' })
// }
// HmMessage.error = text => {
//   HmMessage({ text, type: 'success' })
// }
// HmMessage.warn = text => {
//   HmMessage({ text, type: 'success' })
// }
